<template>
  <el-card>
    <template #header>
      <span>药品代码关联列表</span>
      <el-button
        type="text"
        style="float: right;"
        @click="$router.back()"
      >
        返回
      </el-button>
    </template>

    <!-- 药品代码表格 -->
    <el-table
      v-loading="loading"
      :data="codeList"
      border
      style="width: 100%;"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="drugCode" label="药品代码" />
      <el-table-column prop="drugSerial" label="代码序号" />
      <el-table-column prop="source" label="数据来源" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
            type="text"
            @click="copyCode(scope.row.drugCode)"
            icon="Copy"
            title="复制代码"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 20]"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 15px; text-align: right;"
    />

    <el-empty v-if="!loading && codeList.length === 0" description="暂无药品代码数据" />
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import drugApi from '@/api/drugApi'
import { ElMessage } from 'element-plus'
import { Copy } from '@element-plus/icons-vue'

// 路由参数（获取 ruleId）
const route = useRoute()
const router = useRouter()
const ruleId = ref<number>(Number(route.params.ruleId)) // 从路由获取 ruleId

// 分页状态
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const codeList = ref<drugApi.DrugCode[]>([])
const loading = ref(false)

// 加载药品代码列表（带分页）
const loadCodes = async () => {
  // 校验 ruleId 是否有效
  if (!ruleId.value || isNaN(ruleId.value)) {
    ElMessage.error('规则ID无效，请从规则列表进入')
    router.back()
    return
  }

  loading.value = true
  try {
    // 调用修正后的接口，传递 ruleId、pageNum、pageSize
    const res = await drugApi.getDrugRelationPage({
      ruleId: ruleId.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    codeList.value = res.records || []
    total.value = res.total || 0
  } catch (err) {
    codeList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页事件
const handleSizeChange = (size: number) => {
  pageSize.value = size
  pageNum.value = 1
  loadCodes()
}
const handleCurrentChange = (page: number) => {
  pageNum.value = page
  loadCodes()
}

// 复制药品代码
const copyCode = (code: string) => {
  if (!code) {
    ElMessage.warning('无代码可复制')
    return
  }
  navigator.clipboard.writeText(code).then(() => {
    ElMessage.success('复制成功')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 初始化加载
onMounted(() => {
  loadCodes()
})
</script>
